package com.hxgz.steel.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.hxgz.steel.common.ResponseCode;
import com.hxgz.steel.common.ServerResponse;
import com.hxgz.steel.dao.*;
import com.hxgz.steel.domain.*;
import com.hxgz.steel.dto.QuotationInfoDto;
import com.hxgz.steel.dto.QuotationManageDto;
import com.hxgz.steel.service.QuotationManageService;
import com.hxgz.steel.util.ExcelUtil;
import com.hxgz.steel.util.OSSClientUtil;
import com.hxgz.steel.util.PropertiesUtil;
import com.hxgz.steel.util.UploadPic;
import org.apache.http.entity.ContentType;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 我的报价
 */
@Service
public class QuotationManageServiceImpl implements QuotationManageService {

    @Autowired
    QuotationMapper qMapper;
    @Autowired
    AskInfoMapper aMapper;
    @Autowired
    AskBuyMapper abMapper;
    @Autowired
    QuotationInfoMapper qiMapper;
    @Autowired
    MerchantMapper merchantMapper;
    @Autowired
    OSSClientUtil ossutil;
    @Autowired
    UploadPic upic;
    @Autowired
    OrderMapper orderMapper;

    /**
     * 按照状态查询所有报价信息
     *
     * @param userId
     * @return
     */
    @Override
    public ServerResponse listQuotations(QuotationManageDto vo, Long userId, Page page) {
        PageHelper.startPage(page.getCurrPageNo(), page.getPageSize());
        Map map = new HashMap();
        map.put("status", vo.getStatus() == null || vo.getStatus() < 0 ? null : vo.getStatus());
        map.put("userId", userId);
        map.put("updateTimeStart", vo.getUpdateTimeStart());
        map.put("updateTimeEnd", vo.getUpdateTimeEnd());
        List<QuotationManageDto> list = qMapper.selectListByStatusAndUserId(map);
        for (QuotationManageDto quotationManageDto : list) {
            /*历史求购数*/
            Integer askNumber = abMapper.getAskNumber(quotationManageDto.getUserId());
            /*历史成交数*/
            Integer dealNumber = orderMapper.getDealNumberByNotCancelledAndNotWaitingPaymentAndClosed(quotationManageDto.getUserId());
            if (askNumber == 0) {
                quotationManageDto.setLevel("0");
            } else {
                /*实单率*/
                quotationManageDto.setLevel(new BigDecimal(dealNumber).divide(new BigDecimal(askNumber),0,BigDecimal.ROUND_DOWN).multiply(new BigDecimal("100")).toString());
            }
        }
        PageInfo info = new PageInfo(list);
        return ServerResponse.createBySuccess(info);
    }

    /**
     * 查询报价详情
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public ServerResponse<Map<String, Object>> getQuotationInfo(Long id, Long userId) {
        Map<String, Object> map = new HashMap();
        QuotationInfoDto vo = qMapper.getQuotationInfo(id, userId);
        if (vo == null) {
            vo = new QuotationInfoDto();
        }
        map.put("vo", vo);
        //获取求购的商品列表
        List<AskInfo> list = aMapper.listAskGoodsByAskId(id, userId);
        if (list == null || list.size() == 0) {
            AskInfo info = new AskInfo();
            list.add(info);
        }
        map.put("data", list);
        return ServerResponse.createBySuccess(map);
    }

    /**
     * 下载求购文件
     *
     * @param id
     * @return
     */
    @Override
    public void downloadQuotation(Long id, Long userId, HttpServletResponse response, HttpServletRequest request) {
        List<AskInfo> list = aMapper.selectByAskId(id);
        List<List<String>> dataList = Lists.newArrayList();
        for (AskInfo vo : list) {
            ArrayList<String> list1 = new ArrayList<>();
            list1.add(vo.getKind());
            list1.add(vo.getCommodity());
            list1.add(vo.getProductName());
            list1.add(vo.getTexture());
            list1.add(vo.getSpecification());
            list1.add(vo.getQuantity());
            list1.add(vo.getUnit());
            list1.add(vo.getArea());
            list1.add("0");
            dataList.add(list1);
        }

        String excelName = "求购文件.xls";
        String[] columnName = {"分类", "品名", "商品名称", "材质", "规格", "数量","单位", "地区", "报价(单价)"};
        ExcelUtil util = ExcelUtil.getInstance();
        Workbook workbook = util.dataToExcel2(dataList, excelName, columnName);
        util.exportExcel(workbook, response, excelName);
    }


    @Override
    public void downloadExcel(Long id, Long userId, HttpServletResponse response, HttpServletRequest request) {
        List<AskInfo> list = aMapper.getInfoListByQuotationId(id);
        List<List<String>> dataList = Lists.newArrayList();
        for (AskInfo vo : list) {
            ArrayList<String> list1 = new ArrayList<>();
            list1.add(vo.getKind());
            list1.add(vo.getCommodity());
            list1.add(vo.getProductName());
            list1.add(vo.getTexture());
            list1.add(vo.getSpecification());
            list1.add(vo.getQuantity());
            list1.add(vo.getUnit());
            list1.add(vo.getArea());
            list1.add(vo.getPrice().toString());
            dataList.add(list1);
        }

        String excelName = "报价文件.xls";
        String[] columnName = {"分类", "品名", "商品名称", "材质", "规格", "数量","单位", "地区", "报价(单价)"};
        ExcelUtil util = ExcelUtil.getInstance();
        Workbook workbook = util.dataToExcel2(dataList, excelName, columnName);
        util.exportExcel(workbook, response, excelName);

    }


    /**
     * 拒绝报价
     * @param id
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public ServerResponse refuseQuotation(Long id, Long userId) {
        //获取买家上传求购文件时间，并判断现在是否可操作
        AskBuy askBuy = abMapper.selectByPrimaryKey(id);
        if (askBuy.getUpdateTime() == null || askBuy.getUpdateTime().after(new Date())) {
            return ServerResponse.createByErrorMessage("当前时间不可操作");
        }
        //拒绝报价 修改geo_quotation表的status=2
        Merchant merchant = merchantMapper.getMerchantByuserId(userId);
        int i = qMapper.updateStatusByAskIdAndMerchantId(id, merchant.getId());
        return i > 0 ? ServerResponse.createBySuccessMessage("操作成功") : ServerResponse.createByErrorMessage("操作失败");
    }

    /**
     * 提交报价
     *
     * @param vo
     * @param fileAddress
     * @param userId
     * @return
     */
    @Override
    public ServerResponse submitQuotation(QuotationInfoDto vo, String fileAddress, Long userId) {
        try {
            return this.submit(vo, fileAddress, userId);
        } catch (Exception e) {
            if (vo.getQuotationStatus() != 0) {
                return ServerResponse.createByErrorMessage("已经进行过报价，不能再次进行");
            }
            File file = new File(fileAddress);
            String pealPath = PropertiesUtil.getProperty("file.server.peal") + file.getName();
            Merchant merchant = merchantMapper.getMerchantByuserId(userId);
            Quotation quotation = qMapper.selectByAskBuyIdAndMerchantId(vo.getId(), merchant.getId());
            quotation.setTaxPoint(vo.getTaxPoint());
            quotation.setTaxation(vo.getTaxation());
            quotation.setFreight(vo.getFreight());
            quotation.setTransactionPeriod(Integer.valueOf(vo.getTransactionPeriod().toString()));
            quotation.setTotalPrice(vo.getTotalPrice());
            quotation.setPrice(vo.getPrice());
            Date date = new Date();
            quotation.setUpdateTime(date);
            quotation.setStatus(1);
            quotation.setQuotationFileUrl(pealPath);
            int result = qMapper.updateByPrimaryKeySelective(quotation);
            return ServerResponse.createBySuccessMessage("操作成功");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public ServerResponse submit(QuotationInfoDto vo, String fileAddress, Long userId) {
        File file = new File(fileAddress);
        int result = 0;
        if (file.isFile()) {
            //判断是否报过价
            if (vo.getQuotationStatus() != 0) {
                return ServerResponse.createByErrorMessage("报价状态异常!");
            }
            Long askById = vo.getId();
            Merchant merchant = merchantMapper.getMerchantByuserId(userId);
            Quotation quotation = qMapper.selectByAskBuyIdAndMerchantId(askById, merchant.getId());
            Long qId = quotation.getId();
            List<AskInfo> askInfoList = aMapper.getInfoListByAskId(askById);
            //获取报价内容
            try {
                FileInputStream fileInputStream = new FileInputStream(file);
                MultipartFile multipartFile = new MockMultipartFile(file.getName(), file.getPath(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                List<List<Object>> list = getExcelDataQuotation(multipartFile);
                //            List<List<Object>> list = ExcelUtil.readExcelData(new FileInputStream(address),address);
                List<QuotationInfo> listQuotationInfo = new ArrayList<>();
                QuotationInfo info = null;
                List rowList = list.get(0);//只要第一个sheet页中的数据
                for (int i = 0; i < rowList.size(); i++) {
                    List objList = (List) rowList.get(i);
                    Object[] objArr = objList.toArray();
                    info = new QuotationInfo();

                    info.setPrice(objArr.length <= 8 || objArr[8] == null ? new BigDecimal(0)
                            : new BigDecimal(objArr[8].toString()));

//                    info.setQuotationId(vo.getId());
                    //获取该条数据对应的报价明细的id
                    info.setAskInfoId(aMapper.getIdByQuotation(vo.getId(), i));
                    listQuotationInfo.add(info);
                }
                for (int i = 0; i < listQuotationInfo.size(); i++) {
                    QuotationInfo quotationInfo = listQuotationInfo.get(i);
                    quotationInfo.setQuotationId(qId);
                    quotationInfo.setAskInfoId(askInfoList.get(i).getId());
                }

                //批量新增报价
                int i = 0;
                for (int j = 0; j < listQuotationInfo.size(); j++) {
                    //int num = qiMapper.updatePrice(listInfo.get(j));
                    int num = qiMapper.insertSelective(listQuotationInfo.get(j));
                    i += num;
                }
                //更新报价行情表里的商品报价
                if (vo.getId() != null && vo.getPrice() != null) {
                    Quotation q = qMapper.selectByAskBuyIdAndMerchantId(vo.getId(), merchant.getId());
                    q.setTaxPoint(vo.getTaxPoint());
                    q.setTaxation(vo.getTaxation());
                    q.setFreight(vo.getFreight());
                    q.setTransactionPeriod(Integer.valueOf(vo.getTransactionPeriod().toString()));
                    q.setTotalPrice(vo.getTotalPrice());
                    q.setPrice(vo.getPrice());
                    Date date = new Date();
                    q.setUpdateTime(date);
                    q.setStatus(1);
                    result = qMapper.updateByPrimaryKeySelective(q);
//                    result = qMapper.updateByAskIdAndMerchantId(vo.getId(), vo.getPrice(), merchant.getId());
                }
                return i > 0 && result == 1 ? ServerResponse.createBySuccessMessage("操作成功") : ServerResponse.createByErrorCodeMessage(1, ResponseCode.ERROR.getDesc());
            } catch (Exception e) {
                throw new RuntimeException();
            }
        }
        return ServerResponse.createByErrorCodeMessage(1, ResponseCode.ERROR.getDesc());
    }

    /**
     * 上传报价文件
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ServerResponse importQuotation(MultipartFile multipartFile, HttpServletRequest request) {
        //上传文件到服务器
        UploadPic uploadPic = new UploadPic();
        String filePath = uploadPic.upload(multipartFile);
        return ServerResponse.createBySuccess(filePath);
    }

    /**
     * 手机端   --获取报价列表
     * @param userId
     * @return
     */
  /*  @Override
    public ServerResponse appListQuotations(Long userId) {
        List<AppQuotationListDto> list = qMapper.getListByUserId(userId);
        return ServerResponse.createBySuccess(list == null ? new ArrayList<AppQuotationListDto>() : list);
    }*/


    /**
     * 获取excel中的数据
     *
     * @return
     */
    public List<List<Object>> getExcelData(MultipartFile multipartFile) {
        List<List<Object>> list = new ArrayList();
        List<Object> rowList = null;
        List<Object> cellList = null;
        try {
            InputStream is = multipartFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(is);
            int i = 0;//行数，第一行不添加
            for (Sheet sheet : wb) {
                i = 0;
                rowList = new ArrayList<Object>();
                for (Row row : sheet) {
                    cellList = new ArrayList<Object>();
                    for (Cell cell : row) {
                        String value = getCellData(cell);
                        cellList.add(value);
                    }
                    if (i != 0) {
                        rowList.add(cellList);
                    }
                    i++;
                }
                list.add(rowList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取cell中的数据的值
     *
     * @return
     */
    public String getCellData(Cell cell) {
        switch (cell.getCellType()) {
            // 字符串
            case Cell.CELL_TYPE_STRING:
                return String.valueOf(cell.getRichStringCellValue());
            case Cell.CELL_TYPE_NUMERIC:
                // 日期
                if (DateUtil.isCellDateFormatted(cell)) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                    return String.valueOf(cell.getDateCellValue());
                } else {
                    return String.valueOf(cell.getNumericCellValue());
                }
                // 布尔
            case Cell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            // 公式
            case Cell.CELL_TYPE_FORMULA:
                return String.valueOf(cell.getCellFormula());
            default:
                return "";
        }
    }


    /**
     * 获取excel中的数据
     *
     * @return
     */
    public List<List<Object>> getExcelDataQuotation(MultipartFile multipartFile) {
        List<List<Object>> list = new ArrayList();
        List<Object> rowList = null;
        List<Object> cellList = null;
        try {
            InputStream is = multipartFile.getInputStream();
            HSSFWorkbook wb = new HSSFWorkbook(is);
            int i = 0;//行数，第一行不添加
            for (Sheet sheet : wb) {
                i = 0;
                rowList = new ArrayList<Object>();
                for (Row row : sheet) {
                    cellList = new ArrayList<Object>();
                    for (int j=0;j<9;j++) {
                        String value = "";
                        try {
                            value = getCellData(row.getCell(j));
                        }catch (NullPointerException e){
                        }
                        cellList.add(value);
                    }
                    if (i != 0) {
                        rowList.add(cellList);
                    }
                    i++;
                }
                list.add(rowList);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
